package com.ticket.sass.admin.business.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ticket.sass.admin.annotation.Module;
import com.ticket.sass.admin.business.OperationLogBusiness;
import com.ticket.sass.admin.dto.input.operationlog.OperationLogListInput;
import com.ticket.sass.admin.dto.output.operationlog.OperationLogListOutput;
import com.ticket.sass.admin.dto.output.operationlog.OperationLogModel;
import com.ticket.sass.admin.service.impl.AdminServiceImpl;
import com.ticket.sass.admin.service.impl.OperationLogServiceImpl;
import com.ticket.sass.admin.util.ModelUtil;
import com.ticket.sass.common.entity.tenant.AdminEntity;
import com.ticket.sass.common.entity.tenant.OperationLogEntity;
import lombok.AllArgsConstructor;
import org.modelmapper.TypeToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ywb
 * @date 2024-03-13 16:33
 */
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class OperationLogBusinessImpl implements OperationLogBusiness {
    final ModelUtil modelUtil;
    final AdminServiceImpl adminService;
    final OperationLogServiceImpl operationLogService;
    
    @Override
    public OperationLogModel list(OperationLogListInput input) {
        IPage<OperationLogEntity> page = operationLogService.iPage(input);
        List<OperationLogListOutput> outputs = modelUtil.listToList(
            page.getRecords(),
            new TypeToken<List<OperationLogListOutput>>(){}.getType()
        );
        // 提取会员卡ID列表
        List<Long> adminIds = outputs.stream()
            .map(OperationLogListOutput::getAdminId)
            .collect(Collectors.toList());
        
        Map<Long, AdminEntity> longAdminEntityMap = adminService.mapByIds(adminIds);
        
        outputs.forEach(o -> o.setAdminName(longAdminEntityMap.getOrDefault(o.getAdminId(), new AdminEntity()).getUsername()));
        
        OperationLogModel operationLogModel = new OperationLogModel();
        operationLogModel.setList(outputs);
        operationLogModel.setTotal(page.getTotal());
        operationLogModel.setModules(Module.Companion.getModuleTextList());
        return operationLogModel;
    }
}
